package smedi.ismedi.web.bff.controller.safetycheck;

import com.smedi.ismedi.authoritymanagement.api.dto.response.RoleBasicResponse;
import com.smedi.ismedi.authoritymanagement.api.feign.RemoteAuthorityRoleManagementFeignApi;
import com.smedi.ismedi.constructionproject.api.feign.RemoteProjectAssignmentFeignApi;
import com.smedi.ismedi.file.dto.response.FileInfoResponse;
import com.smedi.ismedi.file.feign.RemoteFileFeignApi;
import com.smedi.ismedi.inmail.api.dto.request.TaskRecordRequest;
import com.smedi.ismedi.inmail.api.feign.RemoteTaskFeignApi;
import com.smedi.ismedi.personnel.api.feign.RemotePersonCoreFeignApi;
import com.smedi.ismedi.safetycheck.dto.request.daily.QueryPageSafetyDailyRequest;
import com.smedi.ismedi.safetycheck.dto.request.daily.QuerySafetyDailyRequest;
import com.smedi.ismedi.safetycheck.dto.request.daily.SafetyDailyRequest;
import com.smedi.ismedi.safetycheck.dto.request.danger.QueryHiddenDangerListRequest;
import com.smedi.ismedi.safetycheck.dto.request.inspection.QueryInspectionRecordListRequest;
import com.smedi.ismedi.safetycheck.dto.response.PaginationResponse;
import com.smedi.ismedi.safetycheck.dto.response.daily.ProjectCalendarResponse;
import com.smedi.ismedi.safetycheck.dto.response.daily.SafetyDailyResponse;
import com.smedi.ismedi.safetycheck.dto.response.danger.HiddenDangerResponse;
import com.smedi.ismedi.safetycheck.dto.response.inspection.InspectionRecordResponse;
import com.smedi.ismedi.safetycheck.feign.RemoteHiddenDangerFeignApi;
import com.smedi.ismedi.safetycheck.feign.RemoteInspectionRecordFeignApi;
import com.smedi.ismedi.safetycheck.feign.RemoteSafetyDailyFeignApi;
import com.smedi.ismedi.web.starter.common.ResponseData;
import com.smedi.ismedi.web.starter.util.DozerUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import smedi.ismedi.web.bff.controller.BaseController;
import smedi.ismedi.web.bff.dto.SafetyDailyDetailResponse;
import smedi.ismedi.web.bff.infrastructure.util.FileHelper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@Api(tags = {"安全日志接口"})
@RequestMapping("/webbff/v1/safetyDaily")
@RequiredArgsConstructor
public class SafetyDailyController extends BaseController {
    private final DozerUtil dozerUtil;

    private final RemoteSafetyDailyFeignApi remoteSafetyDailyFeignApi;
    private final RemoteInspectionRecordFeignApi remoteInspectionRecordFeignApi;
    private final RemoteHiddenDangerFeignApi remoteHiddenDangerFeignApi;
    private final RemoteFileFeignApi fileFeignApi;
    private final RemoteAuthorityRoleManagementFeignApi remoteAuthorityRoleManagementFeignApi;
    private final RemoteProjectAssignmentFeignApi remoteProjectAssignmentFeignApi;
    private final RemoteTaskFeignApi remoteTaskFeignApi;

    @Value("${fdfs.service.address.in}")
    private String FDFS_SERVICE_ADDRESS_IN;

    @Value("${fdfs.service.address.out}")
    private String FDFS_SERVICE_ADDRESS_OUT;

    @ApiOperation(value = "安全日志维护")
    @PostMapping(value = "/safetyDaily")
    ResponseData<SafetyDailyResponse> safetyDaily(@RequestBody SafetyDailyRequest safetyDailyRequest) {
        ResponseData<SafetyDailyResponse> responseData;
        if (safetyDailyRequest.getId() != null) {
            responseData = remoteSafetyDailyFeignApi.updateDaily(safetyDailyRequest);
        } else {
            responseData = remoteSafetyDailyFeignApi.addSafetyDaily(safetyDailyRequest);
        }
        if (safetyDailyRequest.getSubmitted() != null && safetyDailyRequest.getSubmitted()) {
            remoteSafetyDailyFeignApi.commitSafetyDaily(responseData.getData().getId());
        }
        return responseData;
    }

    /**
     * 安全日志列表
     *
     * @param queryPageSafetyDailyRequest
     * @return
     */
    @ApiOperation(value = "查询安全日志列表分页")
    @GetMapping(value = "/getSafetyDailyPage")
    ResponseData<PaginationResponse<SafetyDailyDetailResponse>> getSafetyDailyList(@Validated @SpringQueryMap QueryPageSafetyDailyRequest queryPageSafetyDailyRequest) {
        ResponseData<PaginationResponse<SafetyDailyResponse>> responseDataDailyList = remoteSafetyDailyFeignApi.queryDailyPage(queryPageSafetyDailyRequest);

        PaginationResponse<SafetyDailyResponse> dailyResponsePaginationResponse = responseDataDailyList.getData();

        List<SafetyDailyResponse> safetyDailyResponseList = dailyResponsePaginationResponse.getRecords();

        PaginationResponse<SafetyDailyDetailResponse> paginationResponse = dozerUtil.convertor(dailyResponsePaginationResponse, PaginationResponse.class);

        if (safetyDailyResponseList == null){

            return new ResponseData<>().success(paginationResponse);
        }

        List<SafetyDailyDetailResponse> safetyDailyDetailResponses = dozerUtil.convertor(safetyDailyResponseList, SafetyDailyDetailResponse.class);

        safetyDailyDetailResponses.forEach(x -> {
            QueryInspectionRecordListRequest queryInspectionRecordListRequest = new QueryInspectionRecordListRequest();
            queryInspectionRecordListRequest.setProjectId(x.getProjectId());
            queryInspectionRecordListRequest.setInspectionDate(x.getDailyDate() == null ? null : x.getDailyDate());
            ResponseData<List<InspectionRecordResponse>> listResponseData = remoteInspectionRecordFeignApi.queryRecordList(queryInspectionRecordListRequest);
            x.setInspectionRecordResponses(listResponseData.getData());

            QueryHiddenDangerListRequest queryHiddenDangerListRequest = new QueryHiddenDangerListRequest();
            queryHiddenDangerListRequest.setProjectId(x.getProjectId());
            queryHiddenDangerListRequest.setCheckDate(x.getDailyDate() == null ? null : x.getDailyDate().toString());
            ResponseData<List<HiddenDangerResponse>> hiddenDangerList = remoteHiddenDangerFeignApi.getHiddenDangerList(queryHiddenDangerListRequest);
            x.setHiddenDangerResponses(hiddenDangerList.getData());
        });


        paginationResponse.setRecords(safetyDailyDetailResponses);

        return new ResponseData<>().success(paginationResponse);
    }

    /**
     * 安全日志明细
     *
     * @param querySafetyDailyRequest
     * @return
     */
    @ApiOperation(value = "查询安全日志")
    @GetMapping(value = "/getSafetyDailyDetail")
    ResponseData<SafetyDailyDetailResponse> getSafetyDailyDetail(@Validated @SpringQueryMap QuerySafetyDailyRequest querySafetyDailyRequest) {
        ResponseData<SafetyDailyResponse> responseData = remoteSafetyDailyFeignApi.queryDaily(querySafetyDailyRequest);

        SafetyDailyResponse safetyDailyResponse = responseData.getData();

        SafetyDailyDetailResponse safetyDailyDetailResponse = dozerUtil.convertor(safetyDailyResponse, SafetyDailyDetailResponse.class);

        if (safetyDailyDetailResponse == null) {
            safetyDailyDetailResponse = new SafetyDailyDetailResponse();
            safetyDailyDetailResponse.setProjectId(querySafetyDailyRequest.getProjectId());
            safetyDailyDetailResponse.setDailyDate(querySafetyDailyRequest.getDailyDate() == null ? null : LocalDate.parse(querySafetyDailyRequest.getDailyDate()));
        }

        if (safetyDailyDetailResponse.getDailyDate() != null && safetyDailyDetailResponse.getProjectId() != null) {
            QueryInspectionRecordListRequest queryInspectionRecordListRequest = new QueryInspectionRecordListRequest();
            queryInspectionRecordListRequest.setProjectId(safetyDailyDetailResponse.getProjectId());
            queryInspectionRecordListRequest.setInspectionDate(safetyDailyDetailResponse.getDailyDate());
            ResponseData<List<InspectionRecordResponse>> listResponseData = remoteInspectionRecordFeignApi.queryRecordList(queryInspectionRecordListRequest);
            safetyDailyDetailResponse.setInspectionRecordResponses(listResponseData.getData());

            QueryHiddenDangerListRequest queryHiddenDangerListRequest = new QueryHiddenDangerListRequest();
            queryHiddenDangerListRequest.setProjectId(safetyDailyDetailResponse.getProjectId());
            queryHiddenDangerListRequest.setCheckDate(safetyDailyDetailResponse.getDailyDate().toString());
            ResponseData<List<HiddenDangerResponse>> hiddenDangerList = remoteHiddenDangerFeignApi.getHiddenDangerList(queryHiddenDangerListRequest);
            safetyDailyDetailResponse.setHiddenDangerResponses(hiddenDangerList.getData());
        }

        return new ResponseData<>().success(safetyDailyDetailResponse);
    }

    /**
     * 日志日历状态
     *
     * @param projectId
     * @return
     */
    @ApiOperation(value = "安全日历状态")
    @GetMapping(value = "/getCalendarStatusList")
    ResponseData<ProjectCalendarResponse> getCalendarStatusList(Long projectId, @RequestParam(value = "startTime",required = false) String startTime, @RequestParam(value = "endTime",required = false) String endTime) {
        return remoteSafetyDailyFeignApi.queryCalendarStatus(projectId,startTime,endTime);
    }

    @ApiOperation(httpMethod = "POST", value = "导出安全日志")
    @PostMapping(value = "/exportSafetyDaily")
    public ResponseData<Boolean> exportSafetyDaily(@RequestBody QuerySafetyDailyRequest querySafetyDailyRequest, HttpServletResponse response) throws IOException {
        String signKey = remoteSafetyDailyFeignApi.exportSafetyDaily(querySafetyDailyRequest).getData();
        FileInfoResponse fileInfoResponse = fileFeignApi.getFileInfo(signKey).getData();
        FileHelper.downloadFile(FDFS_SERVICE_ADDRESS_IN, fileInfoResponse.getStorageGroup(), fileInfoResponse.getPath(), fileInfoResponse.getName(), response);
        return new ResponseData<>().success(true);
    }

    @ApiOperation(httpMethod = "POST", value = "安全日志预览")
    @PostMapping(value = "/previewSafetyDaily")
    public ResponseData<String> previewSafetyDaily(@RequestBody QuerySafetyDailyRequest querySafetyDailyRequest, HttpServletResponse response) throws IOException {
        String signKey = remoteSafetyDailyFeignApi.exportSafetyDaily(querySafetyDailyRequest).getData();
        FileInfoResponse fileInfoResponse = fileFeignApi.getFileInfo(signKey).getData();
        String url = FileHelper.getUrl(FDFS_SERVICE_ADDRESS_OUT, fileInfoResponse.getStorageGroup(), fileInfoResponse.getPath(), fileInfoResponse.getName(), response);
        return new ResponseData<>().success(url);
    }

    @DeleteMapping("/deleteDaily")
    @ApiOperation(httpMethod = "DELETE", value = "删除日志")
    ResponseData<Boolean> deleteSafetyDaily(@RequestParam("dailyId") Long id) {
        return remoteSafetyDailyFeignApi.deleteSafetyDaily(id);
    }
}
